package com.pug.config.mvc.interceptor;

import com.pug.constant.PugContants;
import com.pug.redis.PugRedisOperator;
import com.pug.result.ex.KsdValidationException;
import com.pug.utils.ip.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/6$ 2:51$
 */
@Component
@Slf4j
public class PassportInterceptor implements HandlerInterceptor, PugContants {

    @Autowired
    private PugRedisOperator redisOperator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户ip
        String userIp = IpUtils.getIpAddr(request);
        boolean isExist = redisOperator.keyIsExist(PUG_XQ_LOGIN_SMS_LIMIT + userIp);
        if (isExist) {
            throw new KsdValidationException(601, "短信发布频率太大");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
